package com.hnucm.shopapp.ui.register;


import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hnucm.shopapp.R;
import com.hnucm.shopapp.ui.base.BaseActivity;

import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;


public class RegisterActivity extends BaseActivity implements View.OnClickListener, RegisterContract.IRegisterView {
    private ImageView back;
    private EditText userAccount,userPassword,userPassword2;
    private Button register;
    private TextView login;
    private RegisterPresenter registerPresenter;
    @Override
    protected void initViews() {
        back = find(R.id.register_back);
        userAccount = find(R.id.register_edtext_account);
        userPassword = find(R.id.register_edtext_password);
        userPassword2 = find(R.id.register_edtext_password2);
        register = find(R.id.register_btn_register);
        login = find(R.id.register_text_login);
        registerPresenter = new RegisterPresenter(this);
        //监听事件
        back.setOnClickListener(this);
        register.setOnClickListener(this);
        login.setOnClickListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.register_back:
                finish();
                break;
            case R.id.register_text_login:
                finish();
                break;
            case R.id.register_btn_register:
                if(userPassword.getText().toString().equals("")){
                    Toast.makeText(this,"密码不能为空",Toast.LENGTH_SHORT).show();
                }else if(userPassword.getText().toString().equals(userPassword2.getText().toString())){
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("userAccount",userAccount.getText().toString());
                    map.put("userPassword",userPassword.getText().toString());
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject(map).toString());
                    registerPresenter.addUser(requestBody);
                }else{
                    Toast.makeText(this,"两次密码不一致",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void addUserSuccess(boolean bool) {
        if(bool == true){
            Toast.makeText(this,"注册成功",Toast.LENGTH_SHORT).show();
            finish();
        }else{
            Toast.makeText(this,"账号已被注册",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void addUserError(Throwable throwable) {
        Toast.makeText(this,"服务器出错啦",Toast.LENGTH_SHORT).show();
    }
}
